<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据分析</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/stock.css" rel="stylesheet">
    <style>
        .analysis-container {
            margin-top: 20px;
        }
        
        .filter-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .statistics-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .stat-item {
            text-align: center;
            margin-bottom: 15px;
        }
        
        .stat-value {
            font-size: 28px;
            font-weight: bold;
            display: block;
        }
        
        .stat-label {
            font-size: 14px;
            opacity: 0.9;
        }
        
        .gain-positive {
            color: #dc3545;
            font-weight: bold;
        }
        
        .gain-negative {
            color: #28a745;
            font-weight: bold;
        }
        
        .gain-neutral {
            color: #6c757d;
        }
        
        .analysis-table {
            font-size: 13px;
        }
        
        .analysis-table th {
            background-color: #495057;
            color: white;
            border-color: #495057;
        }

        /* 表格行悬停效果 */
        .analysis-table tbody tr:hover {
            background-color: #fff333 !important; /* 黄色背景 */
            transition: background-color 0.2s ease; /* 平滑过渡 */
        }

        .type-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
            white-space: nowrap;
        }

        .text-red {
            color: red; /* 红色 */
        }
        .text-green {
            color: green; /* 绿色 */
        }

        .type-1 { background-color: #ff9800; color: white; }
        .type-2 { background-color: #4caf50; color: white; }
        .type-3 { background-color: #2196f3; color: white; }
        .type-4 { background-color: #e91e63; color: white; }
        .type-0 { background-color: #9e9e9e; color: white; }
        
        /* 名字列宽度设置 */
        .analysis-table th:nth-child(3),
        .analysis-table td:nth-child(3) {
            min-width: 80px;
            width: 80px;
        }

        /* 类型列宽度设置 */
        .analysis-table th:nth-child(4),
        .analysis-table td:nth-child(4) {
            min-width: 130px;
            width: 130px;
        }

        /* 类型列宽度设置 */
        .analysis-table th:nth-child(5),
        .analysis-table td:nth-child(5) {
            min-width: 40px;
            width: 80px;
        }
        
        /* 出现次数列宽度设置 */
        .analysis-table th:nth-child(6),
        .analysis-table td:nth-child(6) {
            min-width: 50px;
            width: 50px;
            text-align: center;
        }

        /* 出现次数列宽度设置 */
        .analysis-table th:nth-child(18),
        .analysis-table td:nth-child(18) {
            min-width: 120px;
            width: 120px;
        }

        .analysis-table th,
        .analysis-table td {
            border: 1px solid #ddd;  /* 细线边框 */
            padding: 8px;
        }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .concept-text {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .pagination-info {
            line-height: 38px;
            color: #6c757d;
            font-size: 14px;
        }
        
        .pagination .page-link {
            color: #007bff;
            border-color: #dee2e6;
        }
        
        .pagination .page-item.active .page-link {
            background-color: #007bff;
            border-color: #007bff;
        }
        
        .pagination .page-item.disabled .page-link {
            color: #6c757d;
            background-color: #fff;
            border-color: #dee2e6;
        }
        
        .sortable {
            cursor: pointer;
            position: relative;
            user-select: none;
        }
        
        .sortable:hover {
            background-color: #5a6268 !important;
        }
        
        .sort-icon {
            margin-left: 5px;
            font-size: 12px;
            opacity: 0.5;
        }
        
        .sort-icon.active {
            opacity: 1;
        }
        
        .sort-asc::after {
            content: "▲";
        }
        
        .sort-desc::after {
            content: "▼";
        }
    </style>
</head>
<body>
<div class="container-fluid analysis-container">
    <div class="row">
        <div class="col-12">
            <h2>
                股票数据分析
<!--                <small class="text-muted">- 选出后价格表现分析</small>-->
                <a href="/" class="btn btn-outline-primary btn-sm float-right">返回主页</a>
                <a href="/limitup/search" class="btn btn-outline-primary btn-sm float-right">涨停查询</a>
                <a href="/gainian" class="btn btn-outline-primary btn-sm float-right">资金流向</a>
                <a href="/stocksflow" class="btn btn-outline-primary btn-sm float-right">个股资金</a>
            </h2>
        </div>
    </div>
    
    <!-- 筛选条件 -->
    <div class="row">
        <div class="col-12">
            <div class="filter-section">
                <form id="filterForm">
                    <div class="row">
                        <div class="col-md-2">
                            <label for="startDate">开始日期：</label>
                            <input type="date" class="form-control" id="startDate" th:value="${startDate}">
                        </div>
                        <div class="col-md-2">
                            <label for="endDate">结束日期：</label>
                            <input type="date" class="form-control" id="endDate" th:value="${endDate}">
                        </div>
                        <div class="col-md-2">
                            <label for="timeFilter">截止时间：</label>
                            <select class="form-control" id="timeFilter">
                                <option value="">全天数据</option>
                                <option value="09:30">09:30前</option>
                                <option value="10:00">10:00前</option>
                                <option value="10:30">10:30前</option>
                                <option value="11:00">11:00前</option>
                                <option value="11:30">11:30前</option>
                                <option value="12:00">12:00前</option>
                                <option value="13:00">13:00前</option>
                                <option value="13:30">13:30前</option>
                                <option value="14:00">14:00前</option>
                                <option value="14:30">14:30前</option>
                                <option value="15:00">15:00前</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="stockSearch">股票代码/名称：=关注-多次+自选</label>
                            <input type="text" class="form-control" id="stockSearch" placeholder="输入股票代码或名称" maxlength="2000">
                        </div>
                        <div class="col-md-2">
                            <label for="conceptSearch">概念板块：=关注</label>
                            <input type="text" class="form-control" id="conceptSearch" placeholder="输入概念关键词" maxlength="30">
                        </div>
                        <div class="col-md-2">
                            <label for="wencaiKeySearch">提示词：</label>
                            <input type="text" class="form-control" id="wencaiKeySearch" placeholder="输入提示词" maxlength="30">
                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-md-2">
                            <label for="typeFilter">股票类型：</label>
                            <select class="form-control" id="typeFilter">
                                <option value="">全部类型</option>
                                <option value="1">重点关注</option>
                                <option value="2">新增量</option>
                                <option value="3">洗盘</option>
                                <option value="4">连续</option>
                                <option value="5">交集</option>
                                <option value="6">差值(前-后)</option>
                                <option value="7">差值(后-前)</option>
                                <option value="8">涨停</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="marketFilter">市场筛选：</label>
                            <select class="form-control" id="marketFilter">
                                <option value="">全部市场</option>
                                <option value="gem">仅创业板</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="conceptFlow">板块资金：</label>
                            <select class="form-control" id="conceptFlow">
                                <option value="">全部类型</option>
                                <option value="1">当天流入</option>
                                <option value="2">当天流出</option>
                            </select>
                        </div>

                        <div class="col-md-2">
                            <label for="pageSize">每页显示：</label>
                            <select class="form-control" id="pageSize">
                                <option value="10">10条</option>
                                <option value="20">20条</option>
                                <option value="50">50条</option>
                                <option value="100">100条</option>
                                <option value="200">200条</option>
                                <option value="500">500条</option>
                                <option value="1000" selected>1000条</option>
                            </select>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="button" class="btn btn-primary" id="searchBtn">查询分析</button>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="button" class="btn btn-success" id="exportBtn">导出数据</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 统计信息 -->
    <div class="row" id="statisticsSection" style="display: none;">
        <div class="col-12">
            <div class="statistics-card">
                <h5>统计概览</h5>
                <div class="row">
                    <div class="col-md-2">
                        <div class="stat-item">
                            <span class="stat-value" id="totalCount">0</span>
                            <span class="stat-label">总数量</span>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="stat-item">
                            <span class="stat-value" id="firstDayAvg">0%</span>
                            <span class="stat-label">当日平均涨幅</span>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="stat-item">
                            <span class="stat-value" id="secondDayAvg">0%</span>
                            <span class="stat-label">第二天平均涨幅</span>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="stat-item">
                            <span class="stat-value" id="thirdDayAvg">0%</span>
                            <span class="stat-label">第三天平均涨幅</span>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="stat-item">
                            <span class="stat-value" id="maxGainAvg">0%</span>
                            <span class="stat-label">最大平均涨幅</span>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <!-- 空列，保持布局对称 -->
                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col-md-3">
                        <div class="stat-item">
                            <span class="stat-value" id="firstDayPositive">0%</span>
                            <span class="stat-label">当日上涨率</span>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-item">
                            <span class="stat-value" id="secondDayPositive">0%</span>
                            <span class="stat-label">第二天上涨率</span>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-item">
                            <span class="stat-value" id="thirdDayPositive">0%</span>
                            <span class="stat-label">第三天上涨率</span>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <!-- 空列，保持布局对称 -->
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 数据表格 -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <div class="input-group">
                        <textarea class="form-control" id="allGainian" rows="3" readonly style="background-color: #f8f9fa;" placeholder="概念汇总"></textarea>
                    </div>
                    <h5 class="mb-0">详细分析数据 <span id="resultCount" class="badge badge-secondary">0</span>
                        <span class="badge bg-secondary" id="allStock" onclick="copyallstock()"><i class="badge fas fa-analytics me-2"></i>复制股票</span>
                        <span class="badge bg-secondary" id="SelectStock" onclick="getSelectedStockCodesJQ()"><i class="badge fas fa-analytics me-2"></i>复制选择</span>
                        <span class="badge bg-secondary" id="addSelectStock" onclick="addupdateFocusStocks()"><i class="badge fas fa-analytics me-2"></i>关注选择</span>
                        <span class="badge bg-secondary" id="remSelectStock" onclick="removeupdateFocusStock()"><i class="badge fas fa-analytics me-2"></i>取消关注</span>
<!--                        <span class="badge bg-secondary" id="SelectGainian" onclick="getAllGainianJQ()"><i class="badge fas fa-analytics me-2"></i>复制概念</span>-->
                    </h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover analysis-table">
                            <thead>
                                <tr>
                                    <th>选择 <input type="checkbox" id="select-all" class="select-all"></th>
                                    <th class="sortable" data-sort="stockCode">代码<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="stockName">名称<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="selectedTime">选出时间<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="typeDescription">类型<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="occurrenceCount">次数<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="selectedPrice">选出价格<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="searchangePercent">选出涨幅<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="firstDayGain">收盘涨幅<span class="sort-icon"></span></th>
                                    <th>第二天最高价</th>
                                    <th>第三天最高价</th>
                                    <th class="sortable" data-sort="secondDayGain">第二天涨幅<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="thirdDayGain">第三天涨幅<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="maxGain">最大涨幅<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="concept">匹配概念<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="allconcept">所有概念<span class="sort-icon"></span></th>
                                    <th>关键词</th>
                                    <th class="sortable" data-sort="rankPosition">热度(今昨差)<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="mainCapitalFlow">资金(主|全)<span class="sort-icon"></span></th>
                                </tr>
                            </thead>
                            <tbody id="analysisTableBody">
                                <tr>
                                    <td colspan="20" class="text-center text-muted">请选择查询条件进行分析</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 分页控件 -->
                    <div class="row mt-3" id="paginationSection" style="display: none;">
                        <div class="col-md-6">
                            <div class="pagination-info">
                                显示第 <span id="pageStart">0</span> - <span id="pageEnd">0</span> 条，共 <span id="totalElements">0</span> 条记录
                            </div>
                        </div>
                        <div class="col-md-6">
                            <nav aria-label="分页导航">
                                <ul class="pagination justify-content-end" id="pagination">
                                    <!-- 分页按钮将通过JavaScript动态生成 -->
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 加载覆盖层 -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
</div>

<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.bundle.min.js"></script>
<script>
// 分页相关的全局变量
let currentPage = 0;
let totalPages = 0;
let totalElements = 0;
let currentPageSize = 1000;

// 排序相关的全局变量
let currentSortField = '';
let currentSortDirection = '';
let allstock = '';
let flowStock = '';
let allOptional = "";
let flowGainian = '';

// 添加全局变量存储当前页数据
let currentPageData = [];
let hasMoreCodes = '';

$(document).ready(function() {

    loadAnalysisData();

    document.getElementById('select-all').addEventListener('click', setupCheckboxHandler);
    // 查询按钮点击事件
    $('#searchBtn').click(function() {
        currentPage = 0; // 重置到第一页
        loadAnalysisData();
    });
    
    // 导出按钮点击事件
    $('#exportBtn').click(function() {
        exportData();
    });
    
    // 每页显示数量变化事件
    $('#pageSize').change(function() {
        currentPageSize = parseInt($(this).val());
        currentPage = 0; // 重置到第一页
        loadAnalysisData();
    });
    
    // 市场筛选变化事件
    $('#marketFilter').change(function() {
        currentPage = 0; // 重置到第一页
        loadAnalysisData();
    });

    // 市场筛选变化事件
    $('#conceptFlow').change(function() {
        currentPage = 0; // 重置到第一页
        loadAnalysisData();
    });
    
    // 时间筛选变化事件
    $('#timeFilter').change(function() {
        currentPage = 0; // 重置到第一页
        loadAnalysisData();
    });
    
    // 排序事件监听器
    $('.sortable').click(function() {
        const sortField = $(this).data('sort');
        
        // 如果点击的是当前排序字段，则切换排序方向
        if (currentSortField === sortField) {
            currentSortDirection = currentSortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            // 如果是新的排序字段，默认降序
            currentSortField = sortField;
            currentSortDirection = 'desc';
        }
        
        // 重置到第一页
        // currentPage = 0;
        
        // 更新排序图标
        updateSortIcons();
        
        // 重新加载数据
        // loadAnalysisData();

        // 本地排序当前页数据
        sortCurrentPageData();
    });


    // 绑定搜索事件
    // 股票搜索框事件
    $('#stockSearch').on('input', handleSearch);

    // 概念搜索框事件
    $('#conceptSearch').on('input', handleSearch);

    // 概念搜索框事件
    $('#wencaiKeySearch').on('input', handleSearch);

    // 页面加载时自动查询
    // loadAnalysisData();
});

// 添加本地排序函数
function sortCurrentPageData() {
    if (currentPageData.length === 0) return;

    // 根据排序字段和方向进行排序
    const sortedData = [...currentPageData].sort((a, b) => {
        let valueA, valueB;

        // 根据不同的排序字段获取对应的值
        switch(currentSortField) {
            case 'stockCode':
                valueA = a.stockCode || '';
                valueB = b.stockCode || '';
                return currentSortDirection === 'asc'
                    ? valueA.localeCompare(valueB)
                    : valueB.localeCompare(valueA);

            case 'selectedTime':
                valueA = a.selectedTime ? new Date(a.selectedTime).getTime() : 0;
                valueB = b.selectedTime ? new Date(b.selectedTime).getTime() : 0;
                break;

            case 'typeDescription':
                valueA = a.typeDescription || '';
                valueB = b.typeDescription || '';
                return currentSortDirection === 'asc'
                    ? valueA.localeCompare(valueB)
                    : valueB.localeCompare(valueA);

            case 'occurrenceCount':
                valueA = a.occurrenceCount || 0;
                valueB = b.occurrenceCount || 0;
                break;

            case 'selectedPrice':
                valueA = parseFloat(a.selectedPrice) || 0;
                valueB = parseFloat(b.selectedPrice) || 0;
                break;

            case 'searchangePercent':
                valueA = parseFloat(a.searchangePercent) || 0;
                valueB = parseFloat(b.searchangePercent) || 0;
                break;

            case 'firstDayGain':
                valueA = parseFloat(a.firstDayGainPercent) || 0;
                valueB = parseFloat(b.firstDayGainPercent) || 0;
                break;

            case 'secondDayGain':
                valueA = parseFloat(a.secondDayGainPercent) || 0;
                valueB = parseFloat(b.secondDayGainPercent) || 0;
                break;

            case 'thirdDayGain':
                valueA = parseFloat(a.thirdDayGainPercent) || 0;
                valueB = parseFloat(b.thirdDayGainPercent) || 0;
                break;

            case 'maxGain':
                valueA = parseFloat(a.maxGainPercent) || 0;
                valueB = parseFloat(b.maxGainPercent) || 0;
                break;

            case 'concept':
                valueA = a.concept || '';
                valueB = b.concept || '';
                return currentSortDirection === 'asc'
                    ? valueA.localeCompare(valueB)
                    : valueB.localeCompare(valueA);
            case 'stockName':
                            valueA = a.stockName || '';
                            valueB = b.stockName || '';
                            return currentSortDirection === 'asc'
                                ? valueA.localeCompare(valueB)
                                : valueB.localeCompare(valueA);
            case 'allconcept':
                valueA = a.allconcept || '';
                valueB = b.allconcept || '';
                return currentSortDirection === 'asc'
                    ? valueA.localeCompare(valueB)
                    : valueB.localeCompare(valueA);

            case 'rankPosition':
                valueA = parseFloat(a.rankPosition) || 0;
                valueB = parseFloat(b.rankPosition) || 0;
                break;

            case 'mainCapitalFlow':
                valueA = parseFloat(a.mainCapitalFlow) || 0;
                valueB = parseFloat(b.mainCapitalFlow) || 0;
                break;

            default:
                return 0;
        }

        // 数字类型排序
        if (currentSortDirection === 'asc') {
            return valueA - valueB;
        } else {
            return valueB - valueA;
        }
    });

    // 重新渲染排序后的表格
    updateAnalysisTable(sortedData);

    // 重新应用搜索过滤
    handleSearch();
}

// 1. 首先修改openSelectedStockCodesJQ函数，支持传入单个代码
function openSelectedStockCodes(selectedCode) {
    let selectedCodes;

    // 如果有传入单个代码，则直接使用该代码
    if (selectedCode) {
        selectedCodes = [selectedCode];
    } else {
        // 否则获取所有选中的代码（保持原逻辑）
        selectedCodes = $('input[name="select-stockCode"]:checked').map(function() {
            return $(this).val();
        }).get();
    }

    // 处理未选中的情况
    if (selectedCodes.length === 0) {
        alert('请先选择股票');
        return;
    }

    // 拼接股票代码为参数（多个代码用逗号分隔）
    const codeParam = selectedCodes.join(',');

    // 构建基于根目录的相对路径
    const targetUrl = `/stocksflow/summarystock?code=${encodeURIComponent(codeParam)}`;

    // 在新标签页打开目标地址
    window.open(targetUrl, '_blank');
}

// 全选/取消全选功能实现
// 全选/取消全选功能实现（只作用于可见数据）
function setupCheckboxHandler() {
    // 获取全选复选框元素
    const selectAllCheckbox = document.getElementById('select-all');

    // 全选复选框变更事件
    selectAllCheckbox.addEventListener('change', function() {
        // 只获取可见行中的复选框
        const visibleCheckboxes = $('#analysisTableBody tr:visible input[name="select-stockCode"]');

        // 将所有可见行复选框的状态设置为与全选复选框一致
        visibleCheckboxes.each(function() {
            $(this).prop('checked', selectAllCheckbox.checked);
        });
    });

    // 监听所有行复选框的变化，更新全选框状态
    $(document).on('change', 'input[name="select-stockCode"]', function() {
        // 只获取可见行中的复选框
        const visibleCheckboxes = $('#analysisTableBody tr:visible input[name="select-stockCode"]');
        // 可见行的总数
        const visibleCount = visibleCheckboxes.length;
        // 可见行中被选中的数量
        const checkedCount = visibleCheckboxes.filter(':checked').length;

        // 只有当所有可见行都被选中时，全选框才选中
        selectAllCheckbox.checked = visibleCount > 0 && visibleCount === checkedCount;
    });
}

// 通用搜索处理函数
function handleSearch() {
    // 获取两个搜索框的值
    let stockSearchText = $('#stockSearch').val().trim().toLowerCase();
    let conceptSearchTerm = $('#conceptSearch').val().trim().toLowerCase();
    let wencaiKeySearchTerm = $('#wencaiKeySearch').val().trim().toLowerCase();
    const $rows = $('#analysisTableBody tr');
    let visibleCount = 0;

    if (stockSearchText==="="){
        stockSearchText = flowStock;
    }

    if (stockSearchText==="-"){
        stockSearchText = hasMoreCodes;
    }
    if (stockSearchText==="+"){
        stockSearchText = allOptional;
    }

    if (conceptSearchTerm==="="){
        conceptSearchTerm = flowGainian;
    }

    $rows.each(function() {
        const $row = $(this);
        let isStockMatch = true;
        let isConceptMatch = true;
        let isKeyMatch = true;

        // 股票搜索过滤
        if (stockSearchText !== '') {
            const stockCode = $row.find('td:eq(1)').text().toLowerCase();
            const stockName = $row.find('td:eq(2)').text().toLowerCase();

            const stockCodeTerms = stockCode.toLowerCase()
                .split(',')
                .map(term => term.trim())
                .filter(Boolean); // 过滤空字符串

            const stockNameTerms = stockName.toLowerCase()
                .split(',')
                .map(term => term.trim())
                .filter(Boolean); // 过滤空字符串
            let stockCodeMatch = stockCodeTerms.some(term => stockSearchText.includes(term));
            let stockNameMatch = stockNameTerms.some(term => stockSearchText.includes(term));
            isStockMatch = stockCode.includes(stockSearchText) || stockName.includes(stockSearchText)|| stockCodeMatch || stockNameMatch;
        }

        // 概念搜索过滤
        if (conceptSearchTerm !== '') {
            const conceptText = $row.find('td:eq(14)').attr('title') || '';
            const allConceptText = $row.find('td:eq(15)').attr('title') || '';

            const combinedText = (conceptText + ' ' + allConceptText).toLowerCase();
            const searchTerms = conceptSearchTerm.toLowerCase()
                .split(',')
                .map(term => term.trim())
                .filter(Boolean); // 过滤空字符串

            // 判断是否有任何一个搜索词存在于概念列表中
            isConceptMatch = searchTerms.some(term => combinedText.includes(term));

            // isConceptMatch = combinedText.includes(conceptSearchTerm);
        }

        // 概念搜索过滤
        if (wencaiKeySearchTerm !== '') {
            const keyText = $row.find('td:eq(16)').attr('title') || '';

            const combinedText = (keyText).toLowerCase();
            const searchTerms = wencaiKeySearchTerm.toLowerCase()
                .split(',')
                .map(term => term.trim())
                .filter(Boolean); // 过滤空字符串

            // 判断是否有任何一个搜索词存在于概念列表中
            isKeyMatch = searchTerms.some(term => combinedText.includes(term));
        }

        // 只有两个条件都满足才显示
        if (isStockMatch && isConceptMatch && isKeyMatch) {
            $row.show();
            visibleCount++;
        } else {
            $row.hide();
        }
    });

    // 更新显示的结果数量
    $('#resultCount').text(visibleCount);

    // 更新分页信息
    const pageStart = currentPage * currentPageSize + 1;
    let pageEnd = Math.min((currentPage + 1) * currentPageSize, totalElements);
    const currentPageVisible = $('#analysisTableBody tr:visible').length;

    $('#pageStart').text(visibleCount > 0 ? pageStart : 0);
    $('#pageEnd').text(visibleCount > 0 ? Math.min(pageEnd, pageStart + currentPageVisible - 1) : 0);
}

function loadAnalysisData(page = currentPage) {
    const startDate = $('#startDate').val();
    const endDate = $('#endDate').val();
    const timeFilter = $('#timeFilter').val();
    const stockSearch = $('#stockSearch').val().trim();
    const wencaiKeySearch = $('#wencaiKeySearch').val().trim();
    const conceptSearch = $('#conceptSearch').val().trim();
    const type = $('#typeFilter').val();
    const conceptFlow = $('#conceptFlow').val();
    const market = $('#marketFilter').val();
    const pageSize = $('#pageSize').val();
    
    if (!startDate || !endDate) {
        alert('请选择开始日期和结束日期');
        return;
    }
    
    // 显示加载状态
    $('#loadingOverlay').show();
    
    // 构建请求参数
    const params = {
        startDate: startDate,
        endDate: endDate,
        page: page,
        size: pageSize
    };
    
    if (timeFilter) {
        params.timeFilter = timeFilter;
    }
    
    if (stockSearch) {
        params.stockSearch = stockSearch;
    }
    
    if (conceptSearch) {
        params.conceptSearch = conceptSearch;
    }

    if (wencaiKeySearch) {
        params.wencaiKeySearch = wencaiKeySearch;
    }

    if (type) {
        params.type = type;
    }
    
    if (market) {
        params.market = market;
    }
    
    // 添加排序参数
    if (currentSortField) {
        params.sortField = currentSortField;
        params.sortDirection = currentSortDirection;
    }
    
    $.ajax({
        url: '/analysis/data',
        method: 'GET',
        data: params,
        success: function(response) {
            if (response.success) {
                flowStock = response.flowStock;
                allOptional = response.allOptional;
                flowGainian = response.flowGainian;
                updateAnalysisTable(response.data);
                $('#allGainian').val(response.conceptCount);
                updateStatistics(response.statistics);
                updatePagination(response.pagination);
                $('#statisticsSection').show();
                $('#paginationSection').show();
            } else {
                alert('查询失败：' + response.message);
            }
        },
        error: function(xhr, status, error) {
            console.error('查询失败:', error);
            alert('查询失败，请检查网络连接');
        },
        complete: function() {
            $('#loadingOverlay').hide();
        }
    });
}

<!-- 1. 添加检测重复股票代码并标记的函数 -->
function markDuplicateStockCodes(data) {
    // 统计每个股票代码出现的次数
    const stockCodeCount = {};

    data.forEach(item => {
        const code = item.stockCode || '';
        stockCodeCount[code] = (stockCodeCount[code] || 0) + 1;
    });

    // 标记哪些股票代码是重复的（出现次数 > 1）
    const duplicateCodes = new Set();
    Object.keys(stockCodeCount).forEach(code => {
        if (stockCodeCount[code] > 1) {
            duplicateCodes.add(code);
            hasMoreCodes+= code+",";
        }
    });

    return duplicateCodes;
}

// 首先提取样式判断逻辑为独立函数，增强可读性和复用性
// 优化后的样式判断函数
function getStockNameStyle(item) {
    // 提前校验必要参数，避免后续错误
    if (!item?.stockCode) {
        return ''; // 股票代码不存在时返回空
    }

    // 校验allOptional是否为有效字符串，再分割（避免split报错）
    if (typeof allOptional === 'string' && allOptional.trim() !== '') {
        const allOptionalCodes = allOptional.split(',').map(code => code.trim());
        if (allOptionalCodes.includes(item.stockCode)) {
            return '#FF0000'; // 纯颜色值，无分号
        }
    }

    // 校验flowStock是否为有效字符串
    if (typeof flowStock === 'string' && flowStock.trim() !== '') {
        const flowStockCodes = flowStock.split(',').map(code => code.trim());
        if (flowStockCodes.includes(item.stockCode)) {
            return '#FFFF00'; // 纯颜色值，无分号
        }
    }

    // 默认无特殊样式（返回空字符串）
    return '';
}



function updateAnalysisTable(data) {
    // 保存当前页数据到全局变量
    currentPageData = [...data];  // 深拷贝数据

    // 检测重复的股票代码
    const duplicateCodes = markDuplicateStockCodes(data);

    const tbody = $('#analysisTableBody');
    tbody.empty();
    
    if (!data || data.length === 0) {
        tbody.append('<tr><td colspan="15" class="text-center text-muted">没有找到相关数据</td></tr>');
        $('#resultCount').text('0');
        return;
    }

    const formatTimeMD = (timeStr) => {
        if (!timeStr) return '-';
        const date = new Date(timeStr);
        // 月份从0开始，需要+1
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0'); // 新增秒数处理
        // 格式化为 "月-日 时:分:秒" 形式，例如 "09-07 15:30:45"
        return `${month}-${day} ${hours}:${minutes}:${seconds}`;
    };
    
    $('#resultCount').text(totalElements || data.length);
    allstock = '';
    data.forEach(function(item) {
        const row = $('<tr>');

        allstock += item.stockCode+",";
        row.append(
            $('<td>').append(
                $('<input>', {
                    type: 'checkbox',
                    class: 'row-checkbox',
                    name: 'select-stockCode',
                    value: item.stockCode || '',
                    'data-id': item.stockCode || ''
                })
            )
        );

        const formatDecimal = (num, digits = 3) => {
            if (num === null || num === undefined) return '-';
            return Number(num).toFixed(digits);
        };

        // 股票代码   // 如果是重复的股票代码，设置背景色为黄色
        // row.append($('<td>').text(item.stockCode || '-')
        //     .css('background-color', duplicateCodes.has(item.stockCode) ? '#ff9800' : ''));
        row.append($('<td>').text(item.stockCode || '-')
            .css('background-color', duplicateCodes.has(item.stockCode) ? '#ff9800' : '')
            .attr('onclick', `openSelectedStockCodes('${item.stockCode || ''}')`));

        // 股票名称
        const ccsT = getStockNameStyle(item);
        row.append($('<td>').text(item.stockName || '-')
            .css('background-color', ccsT)
            .attr('onclick', `openSelectedStockCodes('${item.stockCode || ''}')`));
        
        // 选出时间
        const selectedTimeCell = $('<td>');
        const selectedTime = item.selectedTime ? formatTimeMD(item.selectedTime) : '-';
        const selectedTitype = $('<span>').css('font-size', '12px').text(selectedTime || '未知');
        selectedTimeCell.append(selectedTitype);
        row.append(selectedTimeCell);
        
        // 类型
        const typeCell = $('<td>');
        if (item.type !== null) {
            const typeBadge = $('<span>').addClass('type-badge type-' + item.type).text(item.typeDescription || '未知');
            typeCell.append(typeBadge);
        } else {
            typeCell.text('-');
        }
        row.append(typeCell);
        
        // 出现次数
        const occurrenceCountCell = $('<td>');
        occurrenceCountCell.text(item.occurrenceCount || 0).css('text-align', 'center');
        row.append(occurrenceCountCell);
        
        // 选出时价格
        row.append($('<td>').text(item.selectedPrice ? item.selectedPrice.toFixed(2) : '-'));

        // 选出时涨幅
        // row.append($('<td>').text(item.changePercent ? item.changePercent.toFixed(2) : '-'));
        const searchangePercentCell = $('<td>');
        if (item.searchangePercent !== null) {
            const changePercentText = item.searchangePercent.toFixed(2) + '%';
            const changePercentClass = item.searchangePercent > 0 ? 'gain-positive' :
                item.searchangePercent < 0 ? 'gain-negative' : 'gain-neutral';
            searchangePercentCell.addClass(changePercentClass).text(changePercentText);
        } else {
            searchangePercentCell.text('-');
        }
        row.append(searchangePercentCell);

        // 当日收盘价
        // row.append($('<td>').text(item.firstDayPrice ? item.firstDayPrice.toFixed(2) : '-'));
        
        // 当日涨幅
        const firstDayGainCell = $('<td>');
        if (item.firstDayGainPercent !== null) {
            const gainText = item.firstDayGainPercent.toFixed(2) + '%';
            const gainClass = item.firstDayGainPercent > 0 ? 'gain-positive' : 
                             item.firstDayGainPercent < 0 ? 'gain-negative' : 'gain-neutral';
            firstDayGainCell.addClass(gainClass).text(gainText);
        } else {
            firstDayGainCell.text('-');
        }
        row.append(firstDayGainCell);
        
        // 第二天最高价
        row.append($('<td>').text(item.secondDayHighPrice ? item.secondDayHighPrice.toFixed(2) : '-'));
        
        // 第三天最高价
        row.append($('<td>').text(item.thirdDayHighPrice ? item.thirdDayHighPrice.toFixed(2) : '-'));
        
        // 第二天涨幅
        const secondDayGainCell = $('<td>');
        if (item.secondDayGainPercent !== null) {
            const gainText = item.secondDayGainPercent.toFixed(2) + '%';
            const gainClass = item.secondDayGainPercent > 0 ? 'gain-positive' : 
                             item.secondDayGainPercent < 0 ? 'gain-negative' : 'gain-neutral';
            secondDayGainCell.addClass(gainClass).text(gainText);
        } else {
            secondDayGainCell.text('-');
        }
        row.append(secondDayGainCell);
        
        // 第三天涨幅
        const thirdDayGainCell = $('<td>');
        if (item.thirdDayGainPercent !== null) {
            const gainText = item.thirdDayGainPercent.toFixed(2) + '%';
            const gainClass = item.thirdDayGainPercent > 0 ? 'gain-positive' : 
                             item.thirdDayGainPercent < 0 ? 'gain-negative' : 'gain-neutral';
            thirdDayGainCell.addClass(gainClass).text(gainText);
        } else {
            thirdDayGainCell.text('-');
        }
        row.append(thirdDayGainCell);
        
        // 最大涨幅
        const maxGainCell = $('<td>');
        if (item.maxGainPercent !== null) {
            const gainText = item.maxGainPercent.toFixed(2) + '%';
            const gainClass = item.maxGainPercent > 0 ? 'gain-positive' : 
                             item.maxGainPercent < 0 ? 'gain-negative' : 'gain-neutral';
            maxGainCell.addClass(gainClass).text(gainText);
        } else {
            maxGainCell.text('-');
        }
        row.append(maxGainCell);
        
        // 概念板块
        const conceptCell = $('<td>');
        const conceptText = item.concept || '-';
        const nconceptText = conceptText.length > 16 ? conceptText   .substring(0, 16) + '...' : conceptText;
        conceptCell.addClass('concept-text').attr('title', conceptText).text(nconceptText);
        row.append(conceptCell);

         // 所有概念板块
        const allconceptCell = $('<td>');
        const allconceptText = item.allconcept || '-';
        const displayconceptText = allconceptText.length > 10 ? allconceptText   .substring(0, 10) + '...' : allconceptText;
        allconceptCell.addClass('concept-text').attr('title', allconceptText).text(displayconceptText);
        row.append(allconceptCell);

        // 关键词
        const keywordCell = $('<td>');
        const keywordText = item.keyword || '-';
        // keywordCell.addClass('concept-text').attr('title', keywordText).text(keywordText);
        // row.append(keywordCell);
        const displayText = keywordText.length > 8 ? keywordText.substring(0, 8) + '...' : keywordText;
        keywordCell.addClass('concept-text')
            .attr('title', keywordText)
            .text(displayText);
        row.append(keywordCell);

        // 热度
        const hotCell = $('<td>');
        // const hotText = item.rankPosition+"|"+item.oldRankPosition+"|"+(item.oldRankPosition-item.rankPosition) || '-';
        const hotText1 = item.rankPosition+"|"+item.oldRankPosition+"|";
        const hotText = (item.oldRankPosition-item.rankPosition) || '-';

        const hotClass = (item.oldRankPosition - item.rankPosition) > 0
            ? 'text-red'
            : 'text-green';
        const hotBadge1 = $('<span>').text(hotText1);
        const hotBadge = $('<span>').addClass(hotClass).text(hotText);
        hotCell.append(hotBadge1);
        hotCell.append(hotBadge);
        row.append(hotCell);

        // 资金流向
        const hotflowCell = $('<td>');
        const hotfmlowText = formatDecimal(item.mainCapitalFlow/10000/10000)+"|";//+"|"+formatDecimal(item.capitalFlow/10000/10000);//+"|"+(item.mainCapitalFlow+item.capitalFlow) || '-';
        const hotfmlowClass = formatDecimal(item.mainCapitalFlow/10000/10000)> 0 ? 'text-red' : 'text-green';
        const hotflowText = formatDecimal(item.capitalFlow/10000/10000);//+"|"+formatDecimal(item.capitalFlow/10000/10000);//+"|"+(item.mainCapitalFlow+item.capitalFlow) || '-';
        const hotflowClass = formatDecimal(item.capitalFlow/10000/10000)> 0 ? 'text-red' : 'text-green';
        const hotfmlowBadge = $('<span>').addClass(hotfmlowClass).text(hotfmlowText);
        const hotflowBadge = $('<span>').addClass(hotflowClass).text(hotflowText);
        hotflowCell.append(hotfmlowBadge);
        hotflowCell.append(hotflowBadge);
        row.append(hotflowCell);

        // 7日主力资金流向
        // const sevenDaysFlowCell = $('<td>');
        // const sevenDaysFlowText = formatDecimal(item.sevenDaysMainFlow/10000/10000) || '-';
        // const sevenDaysFlowClass = item.sevenDaysMainFlow > 0 ? 'text-red' : 'text-green';
        // const sevenDaysFlowBadge = $('<span>').addClass(sevenDaysFlowClass).text(sevenDaysFlowText);
        // sevenDaysFlowCell.append(sevenDaysFlowBadge);
        // row.append(sevenDaysFlowCell);

        tbody.append(row);
    });
}

function updateStatistics(stats) {
    if (!stats) return;
    $('#totalCount').text(stats.totalCount || 0);
    $('#firstDayAvg').text((stats.firstDayAverageGain || 0).toFixed(2) + '%');
    $('#secondDayAvg').text((stats.secondDayAverageGain || 0).toFixed(2) + '%');
    $('#thirdDayAvg').text((stats.thirdDayAverageGain || 0).toFixed(2) + '%');
    $('#firstDayPositive').text((stats.firstDayPositiveRate || 0).toFixed(1) + '%');
    $('#secondDayPositive').text((stats.secondDayPositiveRate || 0).toFixed(1) + '%');
    $('#thirdDayPositive').text((stats.thirdDayPositiveRate || 0).toFixed(1) + '%');
    $('#maxGainAvg').text((stats.maxGainAverageGain || 0).toFixed(2) + '%');
}

// 实现复制功能
// // jQuery实现方式
function getSelectedStockCodesJQ() {
    let selectCode = $('input[name="select-stockCode"]:checked').map(function() {
        return $(this).val();
    }).get().join(',');
    copyToClipboard(selectCode);
}

function getAllGainianJQ() {
    // 获取文本框元素
    const allGainianElement = document.getElementById('allGainian');
    // 获取文本框内容
    const content = allGainianElement.value;
    if (content) {
        // 分割内容并去除空项
        const selectCode = processString(content);
        copyToClipboard(selectCode);
    } else {
        console.log('文本框内容为空');
    }
}

function addupdateFocusStocks() {
    var focusStocks = $('input[name="select-stockCode"]:checked').map(function() {
        return $(this).val();
    }).get().join(',');

    if (!focusStocks || focusStocks.trim() === '') {
        alert('没有选择股票代码');
        return;
    }

    focusStocks=(focusStocks ? focusStocks.split('\n').join(',') : '');
    $.ajax({
        url: '/sysinfo/appendBy',
        method: 'GET',
        data: {
            focusStocks: focusStocks
        },
        success: function (response) {
            alert('关注成功');
        },
        error: function (xhr, status, error) {
            console.error('概念查询失败:', error);
            $('#loadingIndicator').removeClass('active');
            reject(error);
        }
    });
}

function removeupdateFocusStock() {
    var focusStocks = $('input[name="select-stockCode"]:checked').map(function() {
        return $(this).val();
    }).get().join(',');

    if (!focusStocks || focusStocks.trim() === '') {
        alert('没有选择股票代码');
        return;
    }

    focusStocks=(focusStocks ? focusStocks.split('\n').join(',') : '');
    $.ajax({
        url: '/sysinfo/removeBy',
        method: 'GET',
        data: {
            focusStocks: focusStocks
        },
        success: function (response) {
            alert('取消关注成功');
        },
        error: function (xhr, status, error) {
            console.error('概念查询失败:', error);
            $('#loadingIndicator').removeClass('active');
            reject(error);
        }
    });
}

function processString(str) {
    // function processString3(str) {
        let result = [];
        let currentPart = '';
        let inBracket = false; // 标记是否在[]内部

        for (let i = 0; i < str.length; i++) {
            const char = str[i];

            if (char === '[') {
                inBracket = true;
                continue; // 跳过[
            }

            if (char === ']') {
                inBracket = false;
                continue; // 跳过]
            }

            if (inBracket) {
                continue; // 跳过[]内部的字符
            }

            if (char === ';') {
                if (currentPart) { // 避免空字符串
                    result.push(currentPart);
                    currentPart = '';
                }
            } else {
                currentPart += char;
            }
        }

        // 处理最后可能剩余的内容
        if (currentPart) {
            result.push(currentPart);
        }
        return result.join(',');
    }


$(document).ready(function() {
    // 为表格行绑定点击事件
    $('table').on('click', 'tr', function(e) {
        // 排除直接点击复选框的情况
        if($(e.target).is('input[type="checkbox"]')) return;

        // 获取当前行的复选框
        var $checkbox = $(this).find('.row-checkbox');

        // 切换选中状态
        $checkbox.prop('checked', !$checkbox.prop('checked'));

        // 可选：添加行高亮样式
        $(this).toggleClass('active', $checkbox.prop('checked'));
    });
});

function copyallstock() {
    let trimmedStr = allstock.replace(/a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, '');
    copyToClipboard(trimmedStr);
    const originalText = $('#allStock').text();
    $('#allStock').text('已复制!');
    setTimeout(() => {
        $('#allStock').text(originalText);
        // allstock="";
    }, 1500);
}

function updatePagination(pagination) {
    if (!pagination) return;
    
    currentPage = pagination.currentPage;
    totalPages = pagination.totalPages;
    totalElements = pagination.totalElements;
    
    // 更新分页信息
    const pageStart = currentPage * pagination.size + 1;
    const pageEnd = Math.min((currentPage + 1) * pagination.size, totalElements);
    $('#pageStart').text(pageStart);
    $('#pageEnd').text(pageEnd);
    $('#totalElements').text(totalElements);
    
    // 构建分页导航
    const paginationNav = $('#pagination');
    paginationNav.empty();
    
    if (totalPages <= 1) {
        return; // 只有一页或没有数据时不显示分页
    }
    
    // 上一页按钮
    const prevItem = $('<li class="page-item">');
    if (!pagination.hasPrevious) {
        prevItem.addClass('disabled');
    }
    const prevLink = $('<a class="page-link" href="#" aria-label="上一页">上一页</a>');
    prevItem.append(prevLink);
    if (pagination.hasPrevious) {
        prevItem.click(function(e) {
            e.preventDefault();
            currentPage--;
            loadAnalysisData();
        });
    }
    paginationNav.append(prevItem);
    
    // 页码按钮
    const startPage = Math.max(0, currentPage - 2);
    const endPage = Math.min(totalPages - 1, currentPage + 2);
    
    // 如果不是从第一页开始，显示第一页和省略号
    if (startPage > 0) {
        const firstPageItem = $('<li class="page-item">');
        const firstPageLink = $('<a class="page-link" href="#">1</a>');
        firstPageItem.append(firstPageLink);
        firstPageItem.click(function(e) {
            e.preventDefault();
            currentPage = 0;
            loadAnalysisData();
        });
        paginationNav.append(firstPageItem);
        
        if (startPage > 1) {
            const ellipsisItem = $('<li class="page-item disabled"><span class="page-link">...</span></li>');
            paginationNav.append(ellipsisItem);
        }
    }
    
    // 显示当前页附近的页码
    for (let i = startPage; i <= endPage; i++) {
        const pageItem = $('<li class="page-item">');
        if (i === currentPage) {
            pageItem.addClass('active');
        }
        const pageLink = $('<a class="page-link" href="#">' + (i + 1) + '</a>');
        pageItem.append(pageLink);
        if (i !== currentPage) {
            pageItem.click(function(e) {
                e.preventDefault();
                currentPage = i;
                loadAnalysisData();
            });
        }
        paginationNav.append(pageItem);
    }
    
    // 如果不是到最后一页，显示省略号和最后一页
    if (endPage < totalPages - 1) {
        if (endPage < totalPages - 2) {
            const ellipsisItem = $('<li class="page-item disabled"><span class="page-link">...</span></li>');
            paginationNav.append(ellipsisItem);
        }
        
        const lastPageItem = $('<li class="page-item">');
        const lastPageLink = $('<a class="page-link" href="#">' + totalPages + '</a>');
        lastPageItem.append(lastPageLink);
        lastPageItem.click(function(e) {
            e.preventDefault();
            currentPage = totalPages - 1;
            loadAnalysisData();
        });
        paginationNav.append(lastPageItem);
    }
    
    // 下一页按钮
    const nextItem = $('<li class="page-item">');
    if (!pagination.hasNext) {
        nextItem.addClass('disabled');
    }
    const nextLink = $('<a class="page-link" href="#" aria-label="下一页">下一页</a>');
    nextItem.append(nextLink);
    if (pagination.hasNext) {
        nextItem.click(function(e) {
            e.preventDefault();
            currentPage++;
            loadAnalysisData();
        });
    }
    paginationNav.append(nextItem);
}

function updateSortIcons() {
    // 清除所有排序图标的状态
    $('.sortable .sort-icon').removeClass('active sort-asc sort-desc');
    
    // 如果有当前排序字段，更新对应的图标
    if (currentSortField) {
        const currentSortHeader = $('.sortable[data-sort="' + currentSortField + '"] .sort-icon');
        currentSortHeader.addClass('active');
        
        if (currentSortDirection === 'asc') {
            currentSortHeader.addClass('sort-asc');
        } else {
            currentSortHeader.addClass('sort-desc');
        }
    }
}

function exportData() {
    const startDate = $('#startDate').val();
    const endDate = $('#endDate').val();
    const timeFilter = $('#timeFilter').val();
    const stockSearch = $('#stockSearch').val().trim();
    const conceptSearch = $('#conceptSearch').val().trim();
    const type = $('#typeFilter').val();
    const market = $('#marketFilter').val();
    
    if (!startDate || !endDate) {
        alert('请选择开始日期和结束日期');
        return;
    }
    
    // 构建下载URL
    let url = '/analysis/export?startDate=' + startDate + '&endDate=' + endDate;
    
    if (timeFilter) {
        url += '&timeFilter=' + timeFilter;
    }
    
    if (stockSearch) {
        url += '&stockSearch=' + encodeURIComponent(stockSearch);
    }
    
    if (conceptSearch) {
        url += '&conceptSearch=' + encodeURIComponent(conceptSearch);
    }
    
    if (type) {
        url += '&type=' + type;
    }
    
    if (market) {
        url += '&market=' + market;
    }
    
    // 打开新窗口下载
    window.open(url, '_blank');
}


// 添加复制功能
function copyToClipboard(stockCodes) {
    // 阻止事件冒泡，避免触发父元素的点击事件
    event.stopPropagation();

    if (!stockCodes || stockCodes.trim() === '') {
        alert('没有股票代码可复制');
        return;
    }

    // 使用现代浏览器的剪贴板API
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(stockCodes).then(() => {
            // 显示成功提示
            showCopySuccessToast(stockCodes.split(',').length);
        }).catch(err => {
            console.error('复制失败:', err);
            fallbackCopy(stockCodes);
        });
    } else {
        // 降级方案
        fallbackCopy(stockCodes);
    }
}

// 降级复制方案
function fallbackCopy(text) {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.left = '-999999px';
    textArea.style.top = '-999999px';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
        document.execCommand('copy');
        showCopySuccessToast(text.split(',').length);
    } catch (err) {
        console.error('降级复制也失败了:', err);
        alert('复制失败，请手动复制：' + text);
    } finally {
        document.body.removeChild(textArea);
    }
}

// 显示复制成功的提示
function showCopySuccessToast(count) {
    // 创建提示元素
    const toast = document.createElement('div');
    toast.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #28a745;
                color: white;
                padding: 12px 20px;
                border-radius: 6px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.3);
                z-index: 9999;
                font-size: 12px;
                font-weight: 500;
                display: flex;
                align-items: center;
                gap: 8px;
                opacity: 0;
                transform: translateX(100%);
                transition: all 0.3s ease;
            `;

    toast.innerHTML = `
                <i class="bi bi-check-circle-fill"></i>
                已复制 ${count} 个股票代码
            `;

    document.body.appendChild(toast);

    // 动画显示
    setTimeout(() => {
        toast.style.opacity = '1';
        toast.style.transform = 'translateX(0)';
    }, 100);

    // 3秒后自动隐藏
    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (document.body.contains(toast)) {
                document.body.removeChild(toast);
            }
        }, 300);
    }, 3000);
}

</script>
</body>
</html> 